package com.ccteam.shared.domain.user

import com.ccteam.model.Resource
import com.ccteam.model.user.UserPasswordVerifyDTO
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.user.UserRepository
import com.ccteam.shared.domain.SuspendUseCase
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/12
 *
 * 修改密码Domain层
 */
class EditPasswordDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val userRepository: UserRepository
): SuspendUseCase<EditPasswordRequest, Nothing?>(
    Dispatchers.IO
) {
    override suspend fun execute(parameters: EditPasswordRequest): Resource<Nothing?> {
        val isLogin = userCore.isLogin.value
        val userInfo = userCore.userInfo.value
        if(!isLogin || userInfo.userToken.isNullOrEmpty()){
            return Resource.Error(ApiError.unknownCode,"操作非法")
        }
        return when(val result = userRepository.editUserPassword(userInfo.userToken,
            UserPasswordVerifyDTO(parameters.phone,parameters.code,parameters.password)
        )){
            is ApiResult.Success ->{
                Resource.Success(null)
            }
            is ApiResult.Empty ->{
                Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
            is ApiResult.Failure ->{
                Resource.Error(ApiError.serverErrorCode,result.errorMsg)
            }
        }
    }
}

data class EditPasswordRequest(
    val phone: String,
    val password: String,
    val code: String
)